package test;

import com.google.gdata.client.Query;
import com.google.gdata.client.calendar.*;
import com.google.gdata.data.*;
import com.google.gdata.data.batch.BatchOperationType;
import com.google.gdata.data.batch.BatchUtils;
import com.google.gdata.data.calendar.*;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;

import java.net.URL;
import java.util.List;

/**
 * 谷歌日历API操作 DEMO地址：https://developers.google.com/google-apps/calendar/v1/
 * developers_guide_java?hl=zh-CN#RetrievingCalendars
 * 
 * @author GodQueue
 * 
 */
public class HahaCalendar {

	private final String username = "kulou54@gmail.com";
	private final String password = "fengyan1901";

	public static void main(String[] args) throws ServiceException, Exception {
		HahaCalendar c = new HahaCalendar();
		CalendarService myService = c.getCalendarService();
		// c.addCalendar(myService);
		// c.quickAddCalendar(myService);
		// c.queryAllCalendarBook(myService);
//		 c.recurringAddCalendar(myService);
		c.queryCalendar(myService);

		// c.addCalendarBook(myService);
		// System.out.println("--------查询一下执行结果-------");
		// c.queryAllCalendarBook(myService);
		//
		// c.updateCalendarBook(myService);
		// System.out.println("--------查询一下执行结果-------");
		// c.queryAllCalendarBook(myService);

		// c.deleteCalendarBook(myService); //
		// 执行方法切记先看下自己的日历本叫什么名字。。不要把自己的日历给删除了。。
		// System.out.println("--------查询一下执行结果-------");
		// c.queryAllCalendarBook(myService);

	}

	/**
	 * 验证帐号和密码
	 * 
	 * @return
	 * @throws Exception
	 */
	public CalendarService getCalendarService() throws Exception {
		CalendarService myService = new CalendarService(
				"exampleCo-exampleApp-1");
		myService.setUserCredentials(username, password);
		return myService;
	}

	/**
	 * 新增日历
	 * 
	 * @param myService
	 * @throws Exception
	 */
	public void addCalendar(CalendarService myService) throws Exception {
		URL postUrl = new URL("https://www.google.com/calendar/feeds/"
				+ username + "/private/full");
		CalendarEventEntry myEntry = new CalendarEventEntry();

		myEntry.setTitle(new PlainTextConstruct("Tennis with Beth"));
		myEntry.setContent(new PlainTextConstruct("Meet for a quick lesson."));

		DateTime startTime = DateTime
				.parseDateTime("2013-07-21T15:00:00+08:00");
		DateTime endTime = DateTime.parseDateTime("2013-07-26T17:00:00+08:00");
		When eventTimes = new When();
		eventTimes.setStartTime(startTime);
		eventTimes.setEndTime(endTime);
		myEntry.addTime(eventTimes);
		//
		//
		// 这段不知道有什么用，执行后，谷歌日历里多了一个小图标，点击显示下面的图片，谷歌叫这个是日历事件的小工具- -～～
		// WebContent wc = new WebContent();
		//
		// wc.setTitle("World Cup");
		// wc.setType("image/gif");
		// wc.setUrl("http://www.google.com/logos/worldcup06.gif");
		// wc.setIcon("http://www.google.com/calendar/images/google-holiday.gif");
		// wc.setWidth("276");
		// wc.setHeight("120");

		// myEntry.setWebContent (wc);

		// Send the request and receive the response:
		CalendarEventEntry insertedEntry = myService.insert(postUrl, myEntry);
	}

	/**
	 * 快速新增日历
	 * 
	 * @param myService
	 * @throws Exception
	 */
	public void quickAddCalendar(CalendarService myService) throws Exception {
		URL postUrl = new URL("https://www.google.com/calendar/feeds/"
				+ username + "/private/full");
		CalendarEventEntry myEntry = new CalendarEventEntry();
		myEntry.setContent(new PlainTextConstruct(
				"Tennis with John April 11 3pm-3:30pm"));
		myEntry.setQuickAdd(true);
		// Send the request and receive the response:
		CalendarEventEntry insertedEntry = myService.insert(postUrl, myEntry);
	}

	/**
	 * 建立周期性日历
	 * 
	 * @param myService
	 * @throws Exception
	 */
	public void recurringAddCalendar(CalendarService myService)
			throws Exception {
		URL postUrl = new URL("https://www.google.com/calendar/feeds/"
				+ username + "/private/full");
		CalendarEventEntry myEntry = new CalendarEventEntry();

		myEntry.setTitle(new PlainTextConstruct("Tennis with Beth"));
		myEntry.setContent(new PlainTextConstruct("Meet for a quick lesson."));

		String recurData = "DTSTART;VALUE=DATE:20130721\r\n"
				+ "DTEND;VALUE=DATE:20130723\r\n"
				+ "RRULE:FREQ=WEEKLY;BYDAY=Tu;UNTIL=20130725\r\n";

		Recurrence recur = new Recurrence();
		recur.setValue(recurData);
		myEntry.setRecurrence(recur);

		// Send the request and receive the response:
		CalendarEventEntry insertedEntry = myService.insert(postUrl, myEntry);
	}

	/**
	 * 更新日历
	 * 
	 * @param myService
	 * @throws Exception
	 */
	public void updateCalendar(CalendarService myService) throws Exception {
		// URL postUrl = new URL(
		// "https://www.google.com/calendar/feeds/"+username+"/private/full");
		// CalendarEventEntry retrievedEntry = new CalendarEventEntry();
		// retrievedEntry.setTitle(new PlainTextConstruct("Important meeting"));
		// URL editUrl = new URL(retrievedEntry.getEditLink().getHref());
		// CalendarEventEntry updatedEntry =
		// (CalendarEventEntry)myService.update(editUrl, myEntry);
	}
	/**
	 * 查询日历
	 * @param myService
	 * @throws Exception
	 */
	public void queryCalendar(CalendarService myService) throws Exception {
		//全文检索 数据
//		URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full");
//		Query myQuery = new Query(feedUrl);
//		myQuery.setFullTextQuery("浦发");
//		CalendarEventFeed myResultsFeed = myService.query(myQuery,
//				CalendarEventFeed.class);
//		if (myResultsFeed.getEntries().size() > 0) {
//			CalendarEventEntry firstMatchEntry = (CalendarEventEntry) myResultsFeed
//					.getEntries().get(0);
//			String myEntryTitle = firstMatchEntry.getTitle().getPlainText();
//			System.out.println(myEntryTitle);
//		}
		
		//根据时间段检索数据
		URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full");

		CalendarQuery myQuery = new CalendarQuery(feedUrl);
		myQuery.setMinimumStartTime(DateTime.parseDateTime("2013-07-20T00:00:00+08:00"));
		myQuery.setMaximumStartTime(DateTime.parseDateTime("2013-07-26T00:00:00+08:00"));
//		com.google.gdata.client.Query
		// Send the request and receive the response:
		
		CalendarEventFeed resultFeed = myService.query(myQuery, CalendarEventFeed.class);
		for (int i = 0; i < resultFeed.getEntries().size(); i++) {
			CalendarEventEntry entry = resultFeed.getEntries().get(i);
			List<When> list = entry.getTimes();
			for (When when : list) {
				System.out.print(when.getStartTime() + "\t");
				System.out.print(when.getEndTime() + "\t");
			}
			System.out.println("\t" + entry.getTitle().getPlainText());
		}
	}

	/**
	 * Retrieving calendar lists 查询所有的日历，这里查询的是类似日历本的意思，你可以在谷歌上创建多个日历，和订阅日历
	 * 在日历的设置里面有一个日历页签，里面可以创建新日历，这个接口就是列出这里的日历本名称
	 * 
	 * @throws Exception
	 */
	public void queryAllCalendarBook(CalendarService myService)
			throws Exception {

		// Send the request and print the response
		URL feedUrl = new URL(
				"https://www.google.com/calendar/feeds/default/allcalendars/full");
		CalendarFeed resultFeed = myService
				.getFeed(feedUrl, CalendarFeed.class);
		System.out.println("Your calendars:");
		System.out.println();
		for (int i = 0; i < resultFeed.getEntries().size(); i++) {
			CalendarEntry entry = resultFeed.getEntries().get(i);
			System.out.println("\t" + entry.getTitle().getPlainText());
		}
	}

	/**
	 * 新建日历本
	 * 
	 * @throws Exception
	 */
	public void addCalendarBook(CalendarService myService) throws Exception {
		CalendarEntry calendar = new CalendarEntry();
		calendar.setTitle(new PlainTextConstruct("haha"));
		calendar.setSummary(new PlainTextConstruct(
				"This calendar contains the practice schedule and game times."));
		calendar.setTimeZone(new TimeZoneProperty("America/Los_Angeles"));
		calendar.setHidden(HiddenProperty.FALSE);
		calendar.setColor(new ColorProperty("#2952A3"));
		calendar.addLocation(new Where("", "", "Oakland"));

		// Insert the calendar
		URL postUrl = new URL(
				"https://www.google.com/calendar/feeds/default/owncalendars/full");
		CalendarEntry returnedCalendar = myService.insert(postUrl, calendar);
	}

	/**
	 * 这里是更新日历本的名称，循环判断如果是之前新增的那个日历本，我现在吧他名字改为new title
	 * 
	 * @param myService
	 * @throws Exception
	 */
	public void updateCalendarBook(CalendarService myService) throws Exception {
		URL feedUrl = new URL(
				"https://www.google.com/calendar/feeds/default/owncalendars/full");
		CalendarFeed resultFeed = myService
				.getFeed(feedUrl, CalendarFeed.class);
		List<CalendarEntry> calendarList = resultFeed.getEntries();
		for (CalendarEntry calendar : calendarList) {
			if (calendar.getTitle().getPlainText().equals("haha")) {
				calendar.setTitle(new PlainTextConstruct("New title"));
				calendar.setColor(new ColorProperty("#A32929"));
				calendar.setSelected(SelectedProperty.TRUE);
				CalendarEntry returnedCalendar = calendar.update();
			}
		}
	}

	/**
	 * 删除日历本
	 * 
	 * @param myService
	 * @throws Exception
	 */
	public void deleteCalendarBook(CalendarService myService) throws Exception {
		URL feedUrl = new URL(
				"https://www.google.com/calendar/feeds/default/owncalendars/full");
		CalendarFeed resultFeed = myService
				.getFeed(feedUrl, CalendarFeed.class);
		for (int i = 0; i < resultFeed.getEntries().size(); i++) {
			CalendarEntry entry = resultFeed.getEntries().get(i);
			System.out.println("Deleting calendar: "
					+ entry.getTitle().getPlainText());

			try {
				if (entry.getTitle().getPlainText().equals("New title")) {
					entry.delete();
				}
			} catch (InvalidEntryException e) {
				System.out.println("\tUnable to delete primary calendar");
			}
		}
	}

}